package com.mall.order.mq.delayOrder;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * Author  kkw
 * Date  2021/6/23 14:47
 * Version 1.0
 * Description :
 */
@Component
@Slf4j
public class DelayOrderProducer {

    @Value("${mq.nameserver.address}")
    private String nameserverAddress;

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
       producer= new DefaultMQProducer("delay_order_producer");
       producer.setNamesrvAddr(nameserverAddress);
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }



    public void sendDelayOrderMsg(String orderId) {
        //此处的msg是rocketMq的依赖
        Message message = new Message();
        message.setTopic("delay_order");
        message.setBody(orderId.getBytes(StandardCharsets.UTF_8));
        //设置延迟级别,和时间
        //1s、 5s、 10s、 30s、 1m、 2m、 3m、 4m、 5m、 6m、 7m、 8m、 9m、 10m、 20m、 30m、 1h、 2h.
        // 1    2   3     4    5    6    7   8    9    10   11  12  13    14   15    16    17  18
        message.setDelayTimeLevel(6);

        SendResult sendResult=null;
        Exception ex=null;
        try {
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            ex=e;
            e.printStackTrace();
        } catch (RemotingException e) {
            ex=e;
            e.printStackTrace();
        } catch (MQBrokerException e) {
            ex=e;
            e.printStackTrace();
        } catch (InterruptedException e) {
            ex=e;
            e.printStackTrace();
        }

        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            log.info("消息发送成功:"+sendResult.getMsgId());
        }
    }
}
